import { create } from 'zustand';
import { projectApi, taskApi } from '@/lib/api';

// 项目类型
export interface Project {
  id: string;
  name: string;
  description?: string;
  status: 'planning' | 'in-progress' | 'completed';
  tasks: {
    total: number;
    completed: number;
  };
}

// 任务类型
export interface Task {
  id: string;
  title: string;
  description?: string;
  status: 'TODO' | 'IN_PROGRESS' | 'REVIEW' | 'DONE';
  priority: 'LOW' | 'MEDIUM' | 'HIGH' | 'URGENT';
  projectId: string;
  assigneeId?: string;
}

// 项目状态
interface ProjectState {
  // 项目相关状态
  projects: Project[];
  currentProject: Project | null;
  projectLoading: boolean;
  projectError: string | null;
  
  // 任务相关状态
  tasks: Task[];
  taskLoading: boolean;
  taskError: string | null;
  
  // 项目操作
  fetchProjects: () => Promise<void>;
  fetchProject: (id: string) => Promise<void>;
  createProject: (project: Omit<Project, 'id'>) => Promise<Project>;
  updateProject: (id: string, project: Partial<Project>) => Promise<void>;
  deleteProject: (id: string) => Promise<void>;
  
  // 任务操作
  fetchTasks: (projectId: string) => Promise<void>;
  createTask: (task: Omit<Task, 'id'>) => Promise<Task>;
  updateTask: (id: string, task: Partial<Task>) => Promise<void>;
  deleteTask: (id: string) => Promise<void>;
  updateTaskStatus: (taskId: string, status: Task['status']) => Promise<void>;
}

// 创建项目状态存储
export const useProjectStore = create<ProjectState>((set, get) => ({
  // 初始状态
  projects: [],
  currentProject: null,
  projectLoading: false,
  projectError: null,
  tasks: [],
  taskLoading: false,
  taskError: null,
  
  // 获取所有项目
  fetchProjects: async () => {
    set({ projectLoading: true, projectError: null });
    try {
      const projects = await projectApi.getProjects();
      set({ projects, projectLoading: false });
    } catch (error) {
      set({ projectLoading: false, projectError: '获取项目失败' });
      console.error('获取项目失败:', error);
    }
  },
  
  // 获取单个项目详情
  fetchProject: async (id: string) => {
    set({ projectLoading: true, projectError: null });
    try {
      const project = await projectApi.getProject(id);
      set({ currentProject: project, projectLoading: false });
    } catch (error) {
      set({ projectLoading: false, projectError: '获取项目详情失败' });
      console.error('获取项目详情失败:', error);
    }
  },
  
  // 创建项目
  createProject: async (project) => {
    set({ projectLoading: true, projectError: null });
    try {
      const newProject = await projectApi.createProject(project);
      set(state => ({
        projects: [...state.projects, newProject],
        projectLoading: false,
      }));
      
      return newProject;
    } catch (error) {
      set({ projectLoading: false, projectError: '创建项目失败' });
      console.error('创建项目失败:', error);
      throw error;
    }
  },
  
  // 更新项目
  updateProject: async (id, project) => {
    set({ projectLoading: true, projectError: null });
    try {
      await projectApi.updateProject(id, project);
      set(state => ({
        projects: state.projects.map(p => p.id === id ? { ...p, ...project } : p),
        currentProject: state.currentProject?.id === id ? { ...state.currentProject, ...project } : state.currentProject,
        projectLoading: false,
      }));
    } catch (error) {
      set({ projectLoading: false, projectError: '更新项目失败' });
      console.error('更新项目失败:', error);
      throw error;
    }
  },
  
  // 删除项目
  deleteProject: async (id) => {
    set({ projectLoading: true, projectError: null });
    try {
      await projectApi.deleteProject(id);
      set(state => ({
        projects: state.projects.filter(p => p.id !== id),
        projectLoading: false,
      }));
    } catch (error) {
      set({ projectLoading: false, projectError: '删除项目失败' });
      console.error('删除项目失败:', error);
      throw error;
    }
  },
  
  // 获取项目任务
  fetchTasks: async (projectId) => {
    set({ taskLoading: true, taskError: null });
    try {
      const tasks = await taskApi.getTasks(projectId);
      set({ tasks, taskLoading: false });
    } catch (error) {
      set({ taskLoading: false, taskError: '获取任务失败' });
      console.error('获取任务失败:', error);
    }
  },
  
  // 创建任务
  createTask: async (task) => {
    set({ taskLoading: true, taskError: null });
    try {
      // 修复createTask调用，不需要单独传projectId
      const newTask = await taskApi.createTask(task);
      
      set(state => ({
        tasks: [...state.tasks, newTask],
        taskLoading: false,
      }));
      
      // 更新项目任务统计
      const { currentProject } = get();
      if (currentProject && currentProject.id === task.projectId) {
        set(state => ({
          currentProject: state.currentProject ? {
            ...state.currentProject,
            tasks: {
              total: state.currentProject.tasks.total + 1,
              completed: task.status === 'DONE' ? state.currentProject.tasks.completed + 1 : state.currentProject.tasks.completed,
            },
          } : null,
        }));
      }
      
      return newTask;
    } catch (error) {
      set({ taskLoading: false, taskError: '创建任务失败' });
      console.error('创建任务失败:', error);
      throw error;
    }
  },
  
  // 更新任务
  updateTask: async (id, task) => {
    set({ taskLoading: true, taskError: null });
    try {
      const oldTask = get().tasks.find(t => t.id === id);
      const updatedTask = await taskApi.updateTask(oldTask?.projectId || task.projectId!, id, task);
      
      // 更新本地状态
      set(state => ({
        tasks: state.tasks.map(t => t.id === id ? { ...t, ...task } : t),
        taskLoading: false,
      }));
      
      // 更新项目任务统计
      const { currentProject } = get();
      const projectId = oldTask?.projectId || task.projectId;
      
      if (currentProject && currentProject.id === projectId && oldTask) {
        // 处理任务状态变化
        const wasCompleted = oldTask.status === 'DONE';
        const isCompleted = task.status === 'DONE' || (oldTask.status === 'DONE' && task.status === undefined);
        
        if (wasCompleted !== isCompleted) {
          set(state => ({
            currentProject: state.currentProject ? {
              ...state.currentProject,
              tasks: {
                ...state.currentProject.tasks,
                completed: isCompleted
                  ? state.currentProject.tasks.completed + 1
                  : state.currentProject.tasks.completed - 1,
              },
            } : null,
          }));
        }
      }
      
      return updatedTask;
    } catch (error) {
      set({ taskLoading: false, taskError: '更新任务失败' });
      console.error('更新任务失败:', error);
      throw error;
    }
  },
  
  // 删除任务
  deleteTask: async (id) => {
    const oldTask = get().tasks.find(t => t.id === id);
    if (!oldTask) throw new Error('任务不存在');
    
    set({ taskLoading: true, taskError: null });
    try {
      await taskApi.deleteTask(oldTask.projectId, id);
      
      // 更新本地状态
      set(state => ({
        tasks: state.tasks.filter(t => t.id !== id),
        taskLoading: false,
      }));
      
      // 更新项目任务统计
      const { currentProject } = get();
      if (currentProject && currentProject.id === oldTask.projectId) {
        set(state => ({
          currentProject: state.currentProject ? {
            ...state.currentProject,
            tasks: {
              total: Math.max(0, state.currentProject.tasks.total - 1),
              completed: oldTask.status === 'DONE'
                ? Math.max(0, state.currentProject.tasks.completed - 1)
                : state.currentProject.tasks.completed,
            },
          } : null,
        }));
      }
    } catch (error) {
      set({ taskLoading: false, taskError: '删除任务失败' });
      console.error('删除任务失败:', error);
      throw error;
    }
  },
  
  // 更新任务状态
  updateTaskStatus: async (taskId, status) => {
    return get().updateTask(taskId, { status });
  },
})); 